package com.lanju.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyuncs.exceptions.ClientException;
import com.lanju.entity.SMSCaptcha;
import com.lanju.entity.User;
import com.lanju.model.ResultModel;
import com.lanju.service.SMSService;
import com.lanju.service.impl.SMSServiceImpl;
import com.lanju.util.CommonUtil;
import com.lanju.util.MessageUtil;
import com.lanju.util.ServletUtil;
import com.lanju.service.PermissionServiceIf;

/**
 * 短信验证码接口
 * */
@Controller
@RequestMapping("/sms")
public class SMSController {
    
	private static final Logger LOGGER = LoggerFactory.getLogger(SMSController.class);
	
    @Autowired
    SMSService smsService;
    
    @Autowired
    PermissionServiceIf permissionService;
    
    
    /** 发送短信验证码  */
    @RequestMapping("/sendCaptcha")
    @ResponseBody
    public ResultModel sendCaptcha(
            @RequestParam(value="phone") String phone,
            @RequestParam(value="type") Integer type){
    		String captcha = CommonUtil.getRandomString(6);
    		Map rsMap;
    		try {
				rsMap = MessageUtil.sendCaptchaSMS(phone, captcha,type);
				if(rsMap.get("Code")!=null && rsMap.get("Code").equals("OK")){
					SMSCaptcha sms = new SMSCaptcha();
					sms.setSmsId(UUID.randomUUID().toString());
					sms.setPhone(phone);
					sms.setCaptcha(captcha);
					sms.setCreateTime(new Date());
					return smsService.addSMSCaptcha(sms);
				}else if(rsMap.get("Code")!=null && rsMap.get("Code").equals("isv.BUSINESS_LIMIT_CONTROL")){
					return ResultModel.fail( "已超过验证码获取量(5条/小时,10条/天)", rsMap );
				}else{
					return ResultModel.fail( (String)rsMap.get("Message"), rsMap );
				}
			} catch (ClientException e) {
				e.printStackTrace();
				LOGGER.error("addSMSCaptcha fail",e);
			}
            return ResultModel.fail();
    }
    
    
    /** 检验该手机号和验证码是否有效 */
    @RequestMapping("/isPhoneCaptcha")
    @ResponseBody
    public ResultModel isPhoneCaptcha(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> param = ServletUtil.getParameterMap(request);
		try{
			boolean flag =  smsService.isPhoneCaptcha(param);
			if(flag){
				 return ResultModel.success();
			}else{
				 return ResultModel.fail();
			}
		}catch (Exception e){
			e.printStackTrace();
			LOGGER.error("isPhoneCaptcha fail",e);
		}
        return ResultModel.fail();
    }
    
    

}
